import {Component, ViewChild} from '@angular/core';
import {Platform, IonicApp, ToastController, Nav} from 'ionic-angular';
import {StatusBar} from '@ionic-native/status-bar';
import {SplashScreen} from '@ionic-native/splash-screen';

import {TabsPage} from '../pages/tabs/tabs';
import {LoginPage} from "../pages/login/login";
import {Utils} from "../framework/utils/Utils";
import {SLLocalStorageUtils} from "../framework/utils/SLLocalStorageUtils";
import {SystemService} from "../pages/service/SystemService";
import {UserManager} from "../framework/manager/UserManager";
import {Log} from "../framework/utils/Log";
import {WebSocketClient} from "../framework/utils/WebSocketClient";
import {Badge} from '@ionic-native/badge';
//declare var cordova: any;

@Component({
    templateUrl: 'app.html'
})
export class MyApp {
    private static TAG: string = "MyApp";
    // private websocket:any;
    // private lockReconnect:any = false;
    // private lockReconnectCount:number=0;
    private userId:string;
    rootPage: any;
    loginStatus: any;
    loginInfo: any;
    @ViewChild('myNav') nav: Nav;
    backButtonPressed: boolean = false;  //用于判断返回键是否触发
    constructor(public ionicApp: IonicApp, public platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public sys: SystemService, public toastCtrl: ToastController) {
        Utils.getPort();
        platform.ready().then(() => {
            this.autoLogin();
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            statusBar.styleDefault();
            this.registerBackButtonAction();//注册返回按键事件
            splashScreen.hide();
        });
        //cordova.plugins.notification.badge.set(10)
    }

    async myNotification() {

       // cordova.plugins.notification.badge.set(10)
        /*   cordova.plugins.notification.local.schedule({
               title: "标题",
               text: "内容",
               foreground: true
           });
       this.badge.hasPermission().then((granted)=>{});*/
        let ip: any = await SLLocalStorageUtils.getInstance().get_Ip();
      //  console.log(  SLLocalStorageUtils.getInstance().get_Ip())
        let port: any = await SLLocalStorageUtils.getInstance().get_Port();
        new WebSocketClient(`ws://${ip}:${port}/bpm/net/message/${this.userId}`);

    }


    registerBackButtonAction() {
        this.platform.registerBackButtonAction(() => {
            //如果想点击返回按钮隐藏toast或loading或Overlay就把下面加上
            // this.ionicApp._toastPortal.getActive() || this.ionicApp._loadingPortal.getActive() || this.ionicApp._overlayPortal.getActive()
            let activePortal = this.ionicApp._modalPortal.getActive();
            if (activePortal) {
                activePortal.dismiss().catch(() => {
                });
                activePortal.onDidDismiss(() => {
                });
                return;
            }
            let activeVC = this.nav.getActive();
			let page = activeVC.instance;
			if (page instanceof LoginPage) {
				return this.showExit();
			}
            let tabs = activeVC.instance.tabs;
            let activeNav = tabs.getSelected();
            return activeNav.canGoBack() ? activeNav.pop() : this.showExit()
        }, 1);
    }

    //双击退出提示框
    showExit() {
        if (this.backButtonPressed) { //当触发标志为true时，即2秒内双击返回按键则退出APP
            this.platform.exitApp();
        } else {
            this.toastCtrl.create({
                message: '再按一次退出应用',
                duration: 2000,
                position: 'top'
            }).present();
            this.backButtonPressed = true;
            setTimeout(() => this.backButtonPressed = false, 2000);//2秒内没有再次点击返回则将触发标志标记为false
        }
    }


    async autoLogin() {
        if (await !Utils.isNullOrUndefined(SLLocalStorageUtils.getInstance().getLoginStatus())) {
            this.loginStatus = await SLLocalStorageUtils.getInstance().getLoginStatus();
            Log.i(MyApp.TAG, '自动登录Bool=='+this.loginStatus );

            if (this.loginStatus) {
                //Log.printObj(MyApp.TAG, '自动登录loginInfo==', this.loginInfo);
                //Log.printObj(MyApp.TAG, '自动登录loginInfo==', this.loginInfo);
                console.log(SLLocalStorageUtils.getInstance().getLoginInfo())
                if (await !Utils.isNullOrUndefined(SLLocalStorageUtils.getInstance().getLoginInfo())) {
                    this.loginInfo = await SLLocalStorageUtils.getInstance().getLoginInfo();
                    this.sys.getLoginInfo(this.loginInfo).subscribe((res: any) => {
                        if (res.msgCode === '1') {
                            Log.printObj(MyApp.TAG, '自动登录loginInfo==', this.loginInfo);
                            UserManager.getInstance().getUserInfo(res.detail);
                            this.userId = res.detail.YongHuBH;
                            this.myNotification();
                            this.rootPage = TabsPage;
                        } else {
                            this.rootPage = LoginPage;
                        }
                    }, error => {
                        this.rootPage = LoginPage;
                        Log.printObj(MyApp.TAG, '自动登录失败==', error);
                    })
                }
            } else {
                this.rootPage = LoginPage;
            }
        }
    }
}
